package net.xyt.report.util;

import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRRtfExporter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;

public class ReportUtils {
	 public static final String HTML_TYPE="html";
	 public static final String PDF_TYPE="pdf";
	 public static final String EXCEL_TYPE="excel";
	 public static final String WORD_TYPE="word";
	 public static final String PRINT_TYPE="print";
	/**
	 * @category 根据文件类型导出文件    
	 * @param type
	 * @param filename
	 * @param jasperPrint
	 * @param response
	 * @throws Exception
	 */
	public static void exportFileByType(String type,String filename,JasperPrint jasperPrint,HttpServletResponse response) throws Exception {
		if(type.equals(PDF_TYPE)) {
        	response.setContentType("application/pdf");
        	String fileName = new String((filename+".pdf").getBytes("GBK"), "ISO8859_1");
            response.setHeader("Content-Disposition", "attachment;filename="+fileName); 
            response.setCharacterEncoding("UTF-8");
            final OutputStream outputStream = response.getOutputStream();
            JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
        }else if(type.equals(EXCEL_TYPE)) {
        	JRXlsExporter xls=new JRXlsExporter();
			xls.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint); 
            xls.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, response.getOutputStream()); 
            xls.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE); 
            xls.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE); 
            String fileName = new String((filename+".xls").getBytes("GBK"), "ISO8859_1");
            response.setHeader("Content-Disposition", "attachment;filename="+fileName); 
            response.setContentType("application/vnd_ms-excel"); 
            xls.exportReport();
        }else if(type.equals(WORD_TYPE)) {
        	response.setContentType("application/msword;charset=utf-8");
            String fileName = new String((filename+".doc").getBytes("GBK"), "ISO8859_1");
            response.setHeader("Content-disposition", "attachment; filename="+fileName);
            JRExporter exporter = new JRRtfExporter();
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
            exporter.exportReport();
        }
	}
}
